package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.api.helper.UserHelper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.MessageAutoreply;
import com.rockcent.mall.lib.domain.MessageReplyRule;
import com.rockcent.mall.lib.domain.enumclass.WechatMessageCode;
import com.rockcent.mall.lib.domain.enumclass.WechatMessageType;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.service.MallWechatMessageConfigService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by marco on 2017/5/24.
 * 微信消息自动回复配置
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MallWechatMessageConfigController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallWechatMessageConfigController.class);

    @Autowired
    private UserHelper userHelper;
    @Autowired
    private MallWechatMessageConfigService mallWechatMessageConfigService;

    /**
     * @api {post} /v1/mall/wechat/message/config/saveOrUpdate M 保存消息自动回复配置
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {String} type <code>必须参数</code> 类型 TEXT("文本"), IMAGE("图片"), VOICE("语音"), VIDEO("视频")
     * @apiParam {String} code <code>必须参数</code> 代码 ADD_FRIEND_REPLY("被动自动回复"), ADD_FRIEND_AUTOREPLY("消息自动回复")
     * @apiParam {String} content 消息内容
     * @apiParam {String} mediaId 素材ID
     * @apiParam {String} mediaTitle 素材标题
     * @apiParam {String} mediaUrl 链接
     * @apiParam {String} mediaDesc 素材描述
     *
     * @apiSuccess {String} success Y表示成功
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_CONFIG_SAVE, method = RequestMethod.POST)
    public JsonResult saveOrUpate(@RequestBody MessageAutoreplyDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String type =  dto.getType();
            String code = dto.getCode();
            dto.setMallId(userDto.mall.getId());
            if(StringUtils.isEmpty(code)) {
                jsonResult.remind("代码不能为空", log);
                return;
            }
            if(!EnumUtils.isValidEnum(WechatMessageCode.class, code)) {
                jsonResult.remind("代码不正确", log);
                return;
            }
            if(StringUtils.isEmpty(type)) {
                jsonResult.remind("类型不能为空", log);
                return;
            }
            if (!EnumUtils.isValidEnum(WechatMessageType.class, type)) {
                jsonResult.remind("类型不正确",log);
                return;
            }
            if(WechatMessageType.valueOf(type)==WechatMessageType.TEXT) {
                String content = dto.getContent();
                if(StringUtils.isEmpty(content)) {
                    jsonResult.remind("内容不能为空",log);
                    return;
                }
                dto.setMediaId("");
                dto.setMediaTitle("");
                dto.setMediaDesc("");
                dto.setMediaUrl("");
            } else if(WechatMessageType.valueOf(type)==WechatMessageType.IMAGE || WechatMessageType.valueOf(type)==WechatMessageType.VOICE) {
                String mediaId = dto.getMediaId();
                if(StringUtils.isEmpty(mediaId)) {
                    jsonResult.remind("素材ID不能为空", log);
                    return;
                }
                dto.setContent("");
                dto.setMediaTitle(StringUtils.isEmpty(dto.getMediaTitle())?"":dto.getMediaTitle());
                dto.setMediaUrl(StringUtils.isEmpty(dto.getMediaUrl())?"":dto.getMediaUrl());
                dto.setMediaDesc(StringUtils.isEmpty(dto.getMediaDesc())?"":dto.getMediaDesc());
            } else if(WechatMessageType.valueOf(type)==WechatMessageType.VIDEO) {
                String mediaId = dto.getMediaId();
                String title = dto.getMediaTitle();
                String desc = dto.getMediaDesc();
                if(StringUtils.isEmpty(mediaId)) {
                    jsonResult.remind("素材ID不能为空", log);
                    return;
                }
                if(StringUtils.isEmpty(title)) {
                    jsonResult.remind("标题不能为空", log);
                    return;
                }
                dto.setMediaDesc(StringUtils.isEmpty(desc)?"":desc);
                dto.setMediaUrl(StringUtils.isEmpty(dto.getMediaUrl())?"":dto.getMediaUrl());
                dto.setContent("");
            } else {
                jsonResult.remind("类型异常",log);
                return;
            }
            mallWechatMessageConfigService.saveOrUpdate(dto);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/mall/wechat/message/config/info M 消息自动回复配置详情
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {String} code <code>必须参数</code> 代码 ADD_FRIEND_REPLY("被动自动回复"), ADD_FRIEND_AUTOREPLY("消息自动回复")
     *
     * @apiSuccess {String} code 代码
     * @apiSuccess {Long}   mallId 平台ID
     * @apiSuccess {String} type 类型 TEXT("文本"), IMAGE("图片"), VOICE("语音"), VIDEO("视频"), NEWS("图文")
     * @apiSuccess {String} content 消息内容
     * @apiSuccess {String} mediaId 素材ID
     * @apiSuccess {String} mediaTitle 素材标题
     * @apiSuccess {String} mediaUrl 链接
     * @apiSuccess {String} mediaDesc 素材描述
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "dateCreated": "2017-05-24 18:25:41",
     *     "lastUpdated": "2017-05-24 18:32:14",
     *     "version": 4,
     *     "code": "ADD_FRIEND_REPLY",
     *     "type": "VIDEO",
     *     "content": "",
     *     "mediaId": "4535345435435345",
     *     "mediaTitle": "tetetwre",
     *     "mediaDesc": "756tuutt",
     *     "mallId": 51
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_CONFIG_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request, MessageAutoreplyDto dto) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String code = dto.getCode();
            if(StringUtils.isEmpty(code)) {
                jsonResult.remind("代码不能为空", log);
                return;
            }
            if(!EnumUtils.isValidEnum(WechatMessageCode.class, code)) {
                jsonResult.remind("代码不正确", log);
                return;
            }
            MessageAutoreply messageAutoreply = mallWechatMessageConfigService.findByCodeAndMallId(code,userDto.mall.getId());
            if(messageAutoreply==null) {
                jsonResult.remind("记录不存在", log);
                return;
            }
            jsonResult.data = messageAutoreply;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/mall/wechat/message/config/del M 删除消息自动回复配置
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {String} code <code>必须参数</code> 代码 ADD_FRIEND_REPLY("被动自动回复"), ADD_FRIEND_AUTOREPLY("消息自动回复")
     *
     * @apiSuccess {String} success Y表示成功
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_CONFIG_DEL, method = RequestMethod.PUT)
    public JsonResult del(HttpServletRequest request, @RequestBody MessageAutoreplyDto dto) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String code = dto.getCode();
            if(StringUtils.isEmpty(code)) {
                jsonResult.remind("代码不能为空", log);
                return;
            }
            if(!EnumUtils.isValidEnum(WechatMessageCode.class, code)) {
                jsonResult.remind("代码不正确", log);
                return;
            }
            MessageAutoreply messageAutoreply = mallWechatMessageConfigService.findByCodeAndMallId(code,userDto.mall.getId());
            if(messageAutoreply==null) {
                jsonResult.remind("记录不存在", log);
                return;
            }
            mallWechatMessageConfigService.delete(code,userDto.mall.getId());
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/mall/wechat/message/rule/saveOrUpdate M 保存消息关键字自动回复配置
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {Long} id 规则ID 修改时必须填上，添加不用填写
     * @apiParam {String} name <code>必须参数</code> 规则名称
     * @apiParam {String} allReply 是否全部回复 YES("是"), NO("否")
     * @apiParam {String} keyword <code>必须参数</code> 关键词
     * @apiParam {String} allMatch 是否全匹配模式 YES("是"), NO("否")
     * @apiParam {String} type <code>必须参数</code> 类型 TEXT("文本"), IMAGE("图片"), VOICE("语音"), VIDEO("视频"), NEWS("图文")
     * @apiParam {String} content 消息内容
     * @apiParam {String} mediaId 素材ID
     * @apiParam {String} mediaTitle 素材标题
     * @apiParam {String} mediaDesc 素材描述
     * @apiParam {String} mediaPicUrl 图片链接
     * @apiParam {String} mediaUrl 图文消息跳转链接
     * @apiParam {String} mediaCreateDate 图文创建时间
     *
     * @apiSuccess {String} success Y表示成功
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_RULE_SAVE, method = RequestMethod.POST)
    public JsonResult save(@RequestBody MessageReplyRuleDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String name = dto.getName();
            String allReply = dto.getAllReply();
            dto.setMallId(userDto.mall.getId());
            List<MessageReplyRuleKeywordDto> keywords = dto.getKeywords();
            List<MessageReplyRuleContentDto> contents = dto.getContents();
            if(StringUtils.isEmpty(name)) {
                jsonResult.remind("规则名称不能为空", log);
                return;
            }
            if(keywords==null || keywords.size()==0) {
                jsonResult.remind("关键词不能为空", log);
                return;
            }
            if(StringUtils.isNotEmpty(allReply) && !EnumUtils.isValidEnum(Whether.class, allReply)) {
                jsonResult.remind("是否全部回复代码不正确", log);
                return;
            }
            for(MessageReplyRuleKeywordDto messageReplyRuleKeywordDto:keywords) {
                if(StringUtils.isEmpty(messageReplyRuleKeywordDto.getKeyword())) {
                    jsonResult.remind("关键词不能为空", log);
                    return;
                }
                String allMatch = messageReplyRuleKeywordDto.getAllMatch();
                if(StringUtils.isNotEmpty(allMatch) && !EnumUtils.isValidEnum(Whether.class, allMatch)) {
                    jsonResult.remind("是否是全匹配模式代码不正确", log);
                    return;
                }
            }
            if(contents==null || contents.size()==0) {
                jsonResult.remind("消息内容不能为空", log);
                return;
            }
            for(MessageReplyRuleContentDto messageReplyRuleContentDto:contents) {
                String type = messageReplyRuleContentDto.getType();
                if(WechatMessageType.valueOf(type)==WechatMessageType.TEXT) {
                    String content = messageReplyRuleContentDto.getContent();
                    if(StringUtils.isEmpty(content)) {
                        jsonResult.remind("内容不能为空",log);
                        return;
                    }
                    messageReplyRuleContentDto.setMediaId("");
                    messageReplyRuleContentDto.setMediaTitle("");
                    messageReplyRuleContentDto.setMediaDesc("");
                } else if(WechatMessageType.valueOf(type)==WechatMessageType.IMAGE || WechatMessageType.valueOf(type)==WechatMessageType.VOICE) {
                    String mediaId = messageReplyRuleContentDto.getMediaId();
                    String mediaIdTitle = messageReplyRuleContentDto.getMediaTitle();
                    if(StringUtils.isEmpty(mediaId)) {
                        jsonResult.remind("素材ID不能为空", log);
                        return;
                    }
                    messageReplyRuleContentDto.setContent("");
                    messageReplyRuleContentDto.setMediaTitle(StringUtils.isEmpty(mediaIdTitle)?"":mediaIdTitle);
                    messageReplyRuleContentDto.setMediaDesc("");
                } else if(WechatMessageType.valueOf(type)==WechatMessageType.VIDEO) {
                    String mediaId = messageReplyRuleContentDto.getMediaId();
                    String title = messageReplyRuleContentDto.getMediaTitle();
                    String desc = messageReplyRuleContentDto.getMediaDesc();
                    if(StringUtils.isEmpty(mediaId)) {
                        jsonResult.remind("素材ID不能为空", log);
                        return;
                    }
                    if(StringUtils.isEmpty(title)) {
                        jsonResult.remind("标题不能为空", log);
                        return;
                    }
                    messageReplyRuleContentDto.setMediaDesc(StringUtils.isEmpty(desc)?"":desc);
                    messageReplyRuleContentDto.setContent("");
                } else if(WechatMessageType.valueOf(type)==WechatMessageType.NEWS) {
                    messageReplyRuleContentDto.setContent("");
                }
            }
            jsonResult.data = mallWechatMessageConfigService.saveOrUpdate(dto);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/mall/wechat/message/rule/del M 删除消息关键词自动回复配置
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {Long} id <code>必须参数</code> 规则ID
     *
     * @apiSuccess {String} success Y表示成功
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_RULE_DEL, method = RequestMethod.PUT)
    public JsonResult delete(HttpServletRequest request, @RequestBody MessageReplyRuleDto dto) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long id = dto.getId();
            if(id==null) {
                jsonResult.remind("规则ID不能为空", log);
                return;
            }
            MessageReplyRule messageReplyRule = mallWechatMessageConfigService.findRuleByIdAndMallId(id,userDto.mall.getId());
            if(messageReplyRule==null) {
                jsonResult.remind("记录不存在", log);
                return;
            }
            mallWechatMessageConfigService.delete(id,userDto.mall.getId());
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/mall/wechat/message/rule/info M 消息关键词自动回复配置详情
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {Long} id <code>必须参数</code> 规则ID
     *
     * @apiSuccess {Long} id 规则ID
     * @apiSuccess {String} name 规则名称
     * @apiSuccess {Long}   mallId 平台ID
     * @apiSuccess {Long}   messageReplyRuleId 规则ID
     * @apiSuccess {String} allReply 是否全部回复 YES("是"), NO("否")
     * @apiSuccess {String} keyword 关键词
     * @apiSuccess {String} allMatch 是否全匹配模式 YES("是"), NO("否")
     * @apiSuccess {String} type 类型 TEXT("文本"), IMAGE("图片"), VOICE("语音"), VIDEO("视频"), NEWS("图文")
     * @apiSuccess {String} content 消息内容
     * @apiSuccess {String} mediaId 素材ID
     * @apiSuccess {String} mediaTitle 素材标题
     * @apiSuccess {String} mediaDesc 素材描述
     * @apiSuccess {String} mediaPicUrl 图片链接
     * @apiSuccess {String} mediaUrl 图文消息跳转链接
     * @apiSuccess {String} mediaCreateDate 图文创建时间
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "name": "rule_test",
     *     "mallId": 51,
     *     "allReply": "NO",
     *     "keywords": [
     *       {
     *         "messageReplyRuleId": 2,
     *         "keyword": "111111",
     *         "allMatch": "YES"
     *       },
     *       {
     *         "messageReplyRuleId": 2,
     *         "keyword": "222222",
     *         "allMatch": "NO"
     *       }
     *     ],
     *     "contents": [
     *       {
     *         "messageReplyRuleId": 2,
     *         "type": "TEXT",
     *         "content": "test123",
     *         "mediaId": "",
     *         "mediaTitle": "",
     *         "mediaDesc": ""
     *       },
     *       {
     *         "messageReplyRuleId": 2,
     *         "type": "IMAGE",
     *         "content": "",
     *         "mediaId": "554353retsfttt",
     *         "mediaTitle": "",
     *         "mediaDesc": "",
     *         "mediaPicUrl": "",
     *         "mediaUrl": ""
     *       }
     *     ]
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_RULE_INFO, method = RequestMethod.GET)
    public JsonResult ruleInfo(HttpServletRequest request, MessageReplyRuleDto dto) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long id = dto.getId();
            if(id==null) {
                jsonResult.remind("ID不能为空", log);
                return;
            }
            MessageReplyRule messageReplyRule = mallWechatMessageConfigService.findRuleByIdAndMallId(id,userDto.mall.getId());
            if(messageReplyRule==null) {
                jsonResult.remind("记录不存在", log);
                return;
            }
            jsonResult.data = mallWechatMessageConfigService.findRuleKeywordContentByIdAndMallId(id,userDto.mall.getId());
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/wechat/message/rule/list M 消息关键词自动回复配置列表
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiSuccess {Long} id 规则ID
     * @apiSuccess {String} name 规则名称
     * @apiSuccess {Long}   mallId 平台ID
     * @apiSuccess {Long}   messageReplyRuleId 规则ID
     * @apiSuccess {String} allReply 是否全部回复 YES("是"), NO("否")
     * @apiSuccess {String} keyword 关键词
     * @apiSuccess {String} allMatch 是否全匹配模式 YES("是"), NO("否")
     * @apiSuccess {String} type 类型 TEXT("文本"), IMAGE("图片"), VOICE("语音"), VIDEO("视频"), NEWS("图文")
     * @apiSuccess {String} content 消息内容
     * @apiSuccess {String} mediaId 素材ID
     * @apiSuccess {String} mediaTitle 素材标题
     * @apiSuccess {String} mediaDesc 素材描述
     * @apiSuccess {String} mediaPicUrl 图片链接
     * @apiSuccess {String} mediaUrl 图文消息跳转链接
     * @apiSuccess {String} mediaCreateDate 图文创建时间
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [{
     *     "id": 1,
     *     "name": "rule_test",
     *     "mallId": 51,
     *     "allReply": "NO",
     *     "keywords": [
     *       {
     *         "messageReplyRuleId": 2,
     *         "keyword": "111111",
     *         "allMatch": "YES"
     *       },
     *       {
     *         "messageReplyRuleId": 2,
     *         "keyword": "222222",
     *         "allMatch": "NO"
     *       }
     *     ],
     *     "contents": [
     *       {
     *         "messageReplyRuleId": 2,
     *         "type": "TEXT",
     *         "content": "test123",
     *         "mediaId": "",
     *         "mediaTitle": "",
     *         "mediaDesc": ""
     *       },
     *       {
     *         "messageReplyRuleId": 2,
     *         "type": "IMAGE",
     *         "content": "",
     *         "mediaId": "554353retsfttt",
     *         "mediaTitle": "",
     *         "mediaDesc": "",
     *         "mediaPicUrl": "",
     *         "mediaUrl": ""
     *       }
     *     ]
     *   },...]
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MESSAGE_RULE_LIST, method = RequestMethod.GET)
    public JsonResult rules(HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            jsonResult.data = mallWechatMessageConfigService.findRulesByMallId(userDto.mall.getId());
        };
        return doing.go(request, log);
    }
}
